<template>
  <el-dialog title="选择商品" :visible.sync="showDialog" :before-close="closeDialog" :close-on-click-modal="false"
    width="1200px" top="100px">
    <el-row type="flex" justify="space-around">
      <el-col :span="24">
        <el-form class="search clearfix" :inline="true" label-suffix="：" size="mini" :model="search">
          <!-- 商品筛选条件 -->
          <el-row>
            <el-form-item>
              <el-select v-model="search.productStatus" class="w120" clearable placeholder="全部状态">
                <el-option v-for="item in options.productStatus" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input v-model="search.productName" class="w300" clearable placeholder="搜索编码/名称/条码/助记码/别名"
                @keyup.enter.native="getList('search')">
                <el-button slot="append" icon="el-icon-search" @click="getList('search')" />
              </el-input>
            </el-form-item>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="space-around" class="border-bottom pb20">
      <el-col :span="4">
        <div class="tree-header">分类筛选</div>
        <el-tree :data="options.category" :props="{children: 'children', label: 'name'}" :expand-on-click-node="false"
          highlight-current default-expand-all @node-click="changeTreeNode" />
      </el-col>
      <el-col :span="20">
        <el-table ref="productList" size="small" height="500" :data="list" :cell-style="$style.cellStyle"
          :header-cell-style="$style.rowClass" @select="selectRow" @select-all="selectAll">
          <el-table-column type="selection" :selectable="handleSelectable" width="55" />
          <ElTableColumn width="30">
            <template slot-scope="{row}">
              <el-popover v-if="row.isExist > 0&&searchParams.type !== 'combo'" placement="right" trigger="hover"
                content="规则重复，请检查适用门店和主商品！">
                <i slot="reference" class="el-icon-info fz16 mr10 cDD2020" />
              </el-popover>
            </template>
          </ElTableColumn>
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column label="商品编码" prop="productCode" width="200" />
          <el-table-column label="规格单位" prop="unitName" />
          <el-table-column label="状态" prop="productStatus">
            <template slot-scope="{row}">
              <el-tag :type="options.productStatus[row.productStatus * 1].type">
                {{ options.productStatus[row.productStatus * 1].name }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination class="page tc mt10" :total="page.total" :page.sync="page.current" :limit.sync="page.size"
          @pagination="getList" />
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="getSelect()">确 定</el-button>
      <el-button size="small" @click="closeDialog()">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
class Search {
  constructor() {
    this.productStatus = 0; // 商品状态(0.正常1.停售2.淘汰3.删除)
    this.relCategory = ''; // 分类编号(一级分类或者二级分类)
    this.productName = ''; // 商品名称,商品编码,助记码,sku条码
  }
}
class Page {
  constructor() {
    this.total = 0;
    this.current = 1;
    this.size = 10;
  }
}
class Options {
  constructor() {
    this.category = [];
    this.productStatus = [
      { id: 0, name: '正常', type: 'success' },
      { id: 1, name: '停售', type: 'danger' },
      { id: 2, name: '淘汰', type: 'warning' },
      { id: 3, name: '删除', type: 'info' }
    ]; // 商品状态
    this.storeStatus = [
      { id: 1, name: '正常', type: 'success' },
      { id: 2, name: '停用', type: 'danger' }
    ]; // 门店状态
    this.storeType = [
      { id: 1, name: '直营店', type: 'danger' },
      { id: 2, name: '加盟店', type: 'warning' }
    ]; // 门店类型
  }
}
import {
  categoryCacheList,
  productListPage,
  productAndSkuListPage,
  combinationSonProductListPage,
  combinationRootProductListPage,
  splitRootProductListPage,
  selectAddOrderRuleProductListPage
} from '@/api/goods';
import pagination from '@/components/Pagination';
export default {
  name: 'Search',
  components: {
    pagination
  },
  props: {
    searchParams: {
      type: Object,
      default: () => {
        return {};
      }
    }, // 搜索附加参数 ,对象形式，默认为空
    selectMode: {
      type: String,
      default: 'single'
    }, // 选择模式，single 单选；multiple 多选
    showDialog: {
      type: Boolean,
      default: false
    }, // 开关
    defaultDatas: {
      type: Array,
      default: () => []
    }, // 默认回显数据
    showSelected: {
      type: Boolean,
      default: false
    } // 回显标识

  },
  data () {
    return {
      page: new Page(), // 列表分页
      search: new Search(), // 列表搜索
      options: new Options(), // 搜索项
      list: [], // 商品列表
      selectedDatas: []
    };
  },
  watch: {
    showDialog (newVal) {
      if (newVal) {
        this.getOptions();
        this.open();
      }
    }
  },
  created () {
    // this.getOptions();
    // this.getList();
  },
  methods: {
    open () {
      this.selectedDatas = [];
      if (this.defaultDatas.length > 0) {
        this.selectedDatas = JSON.parse(JSON.stringify(this.defaultDatas));
      }
      this.checkedProduct();
    },
    // 用于已选商品进行回显
    checkedProduct () {
      if (this.showSelected) {
        // 匹配skuId
        if (this.searchParams.type === 'sku') {
          const ids = this.selectedDatas.map(val => val.skuId);
          this.list.forEach(item => {
            if (ids.includes(item.skuId)) {
              this.$nextTick(() => {
                this.$refs['productList'].toggleRowSelection(item, true);
              });
            }
          });
        } else {
          // 匹配pruductId
          const ids = this.selectedDatas.map(val => val.productId);
          this.list.forEach(item => {
            if (ids.includes(item.productId)) {
              this.$nextTick(() => {
                this.$refs['productList'].toggleRowSelection(item, true);
              });
            }
          });
        }
      }
    },
    // 获取条件选项
    async getOptions () {
      this.options.category = [{ name: '全部分类', catid: '' }, ...await categoryCacheList()];
      this.getList();
    },
    // 获取商品列表
    async getList (type) {
      if (type === 'search') this.page = new Page();
      try {
        let data;
        const params = { ...this.page, ...this.search, ...this.searchParams };
        if (this.searchParams.type === 'combo') {
          data = await combinationSonProductListPage(params); // 组合规则子商品
        } else if (this.searchParams.type === 'root') {
          data = await combinationRootProductListPage(params); // 组合规则主商品
        } else if (this.searchParams.type === 'split') {
          data = await splitRootProductListPage(params); // 拆分规则子商品
        } else if (this.searchParams.type === 'sku') {
          data = await productAndSkuListPage(params); // 商品sku列表
        } else if (this.searchParams.type === 'purchase') {
          data = await selectAddOrderRuleProductListPage(params); // 订货规则商品
        } else {
          data = await productListPage(params);
        }
        const { records, total } = data;
        this.page.total = total * 1;
        this.list = records;
        this.checkedProduct();
      } catch (e) {
        this.page.total = 0;
        this.list = [];
      }
    },
    // 切换左侧分类
    changeTreeNode (val) {
      this.search.relCategory = val.catid;
      this.getList();
    },
    // 是否可选
    handleSelectable (row, index) {
      return row.isExist < 1 || !row.isExist;
    },

    // 关闭弹窗
    closeDialog () {
      this.search = new Search();
      this.$refs['productList'].clearSelection();
      this.$emit('closeDialog');
    },
    // 当用户手动勾选数据行的 Checkbox 时触发的事件
    selectRow (selection, row) {
      if (this.selectMode === 'single') {
        this.selectedDatas = [];
        this.selectedDatas = selection;
      }
      if (this.searchParams.type === 'sku') {
        // 匹配skuId
        const ids = selection.map(val => val.skuId);
        if (ids.includes(row.skuId)) {
          this.addSelectGood([row]);
        } else {
          this.delSelectGood([row]);
        }
      } else {
        // 匹配productId
        const ids = selection.map(val => val.productId);
        if (ids.includes(row.productId)) {
          this.addSelectGood([row]);
        } else {
          this.delSelectGood([row]);
        }
      }
    },
    // 多选添加
    addSelectGood (arr) {
      if (this.searchParams.type === 'sku') {
        // 匹配skuId
        const ids = this.selectedDatas.map(val => val.skuId);
        arr.forEach(item => {
          if (!ids.includes(item.skuId)) {
            this.selectedDatas.push(item);
          }
        });
      } else {
        // 匹配productId
        const ids = this.selectedDatas.map(val => val.productId);
        arr.forEach(item => {
          if (!ids.includes(item.productId)) {
            this.selectedDatas.push(item);
          }
        });
      }
      // 判断isExist是否存在并是否可选  如存在删掉该条数据
      this.selectedDatas.forEach((val, index) => {
        if (val.isExist == 1 && val.isExist) {
          this.selectedDatas.splice(index, 1);
        }
      });
    },
    // 多选删除
    delSelectGood (arr) {
      if (this.searchParams.type === 'sku') {
        // 匹配skuId
        const ids = this.selectedDatas.map(val => val.skuId);
        arr.forEach(item => {
          if (ids.includes(item.skuId)) {
            const index = this.selectedDatas.findIndex(val => val.skuId === item.skuId);
            this.selectedDatas.splice(index, 1);
          }
        });
      } else {
        // 匹配productId
        const ids = this.selectedDatas.map(val => val.productId);
        arr.forEach(item => {
          if (ids.includes(item.productId)) {
            const index = this.selectedDatas.findIndex(val => val.productId === item.productId);
            this.selectedDatas.splice(index, 1);
          }
        });
      }
    },
    // 当用户手动勾选全选 Checkbox 时触发的事件
    selectAll (selection) {
      if (selection.length <= 0) {
        this.delSelectGood(this.list);
      } else {
        this.addSelectGood(this.list);
      }
    },
    // 确定选项
    getSelect () {
      if (this.selectMode === 'single' && this.selectedDatas.length > 1) return this.$notification('选择过多', 'warning', '目前只支持选取单项。');
      // 数组去重
      Array.from(new Set(this.selectedDatas));
      let arr = {};
      arr.option = this.selectedDatas; // 选项赋值，用于筛选框回显
      if (this.searchParams.type === 'sku') { // 匹配skuId
        arr.selected = this.selectedDatas.map(val => val.skuId); // 筛选项赋值，用于筛选框回显
      } else { // 匹配productId
        arr.selected = this.selectedDatas.map(val => val.productId); // 筛选项赋值，用于筛选框回显
      }
      this.$emit('getSelect', arr);
      this.closeDialog();
    }
  }
};
</script>

<style scoped lang="scss">
.tree-header {
  height: 40px;
  background: #f9fafc;
  color: #909399;
  font-size: 12px;
  font-weight: bold;
  line-height: 40px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
}
.border-bottom {
  border-bottom: 1px solid #ebeef5;
}
</style>
